package matchthreegame.handlers;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import matchthreegame.dataBase.DBManagerHelper;
import matchthreegame.extensions.MatchThreeGameZoneExtension;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSArray;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;

public class GetListOfUsersForNameHandler extends BaseClientRequestHandler {

	public static final String CMD_GET_LIST_OF_USERS_FOR_NAME = "GLUN";
	public static final String LIST_OF_USER_NAMES             = "LOUN";
	
	
	MatchThreeGameZoneExtension zoneExtension;
	
	@Override
	public void handleClientRequest(User sender, ISFSObject requestParams) {
		
		zoneExtension = (MatchThreeGameZoneExtension)getParentExtension().getParentZone().getExtension();
		
		// get username to search for
		String username = requestParams.getUtfString(zoneExtension.USERNAME);
		
		WeakReference<DBManagerHelper> dbHelper = null;
		ArrayList<String> usernames = null;
		
		try {
			dbHelper = new WeakReference<DBManagerHelper>(zoneExtension.getDBHelper());
			
			// Get array with usernames containing the string 'username'
			usernames = dbHelper.get().getListOfUsersForName(username);
			
		} catch (Exception e) {
			trace(e.getMessage().toString());
		}
		
		SFSArray sfsListOfUsers = new SFSArray();
		
		if ( usernames != null ) {
									
			// Put all found usernames in SFSArray with strings
			for (int i = 0; i < usernames.size(); i++) {
				sfsListOfUsers.addUtfString(usernames.get(i));
			}

		} else {
			trace("There is NO users containg: " + username);
		}
				
		// Send SFSArray in SFSObject with the found usernames back to the sender
		SFSObject sfsParams = new SFSObject();
		sfsParams.putSFSArray(LIST_OF_USER_NAMES,sfsListOfUsers);
		
		zoneExtension.send(CMD_GET_LIST_OF_USERS_FOR_NAME, sfsParams, sender);
	}

}
